package com.ticket.sass.admin.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ticket.sass.admin.business.AppBusiness;
import com.ticket.sass.admin.dto.input.feature.AppEnableInput;
import com.ticket.sass.admin.dto.output.feature.AppListOutput;
import com.ticket.sass.admin.model.PageModel;
import com.ticket.sass.admin.service.impl.AppCinemaMapServiceImpl;
import com.ticket.sass.admin.service.impl.AppServiceImpl;
import com.ticket.sass.admin.util.CinemaIdUtil;
import com.ticket.sass.admin.util.EscapeUtil;
import com.ticket.sass.admin.util.ModelUtil;
import com.ticket.sass.common.entity.tenant.AppEntity;
import com.ticket.sass.common.exception.enums.ErrorCode;
import com.ticket.sass.common.exception.exception.BadRequestException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2024-03-15 10:35
 */
@Slf4j
@Service
@AllArgsConstructor
public class AppBusinessImpl implements AppBusiness {
    final ModelUtil modelUtil;
    final AppServiceImpl service;
    final AppCinemaMapServiceImpl appCinemaMapService;
    
    @Override
    public PageModel<AppListOutput> list() {
        Long cinemaId = CinemaIdUtil.getCinemaIdFromRequest();
        List<AppListOutput> outputs = service.list().stream().map(AppListOutput::new).collect(Collectors.toList());
        Map<Long, Boolean> enabledStatusForAppIds = appCinemaMapService.getEnabledStatusForAppIds(outputs.stream().map(AppListOutput::getId).collect(Collectors.toList()), cinemaId);
        outputs.forEach(o -> o.setEnable(enabledStatusForAppIds.getOrDefault(o.getId(), Boolean.FALSE)));
        return new PageModel<>((long) outputs.size(), outputs);
    }
    
    
    @Override
    public void setEnable(AppEnableInput input) {
        validateId(input.getId());
        Long cinemaId = CinemaIdUtil.getCinemaIdFromRequest();
        appCinemaMapService.updateOrCreateRecord(cinemaId, input.getId(), input.getEnable());
    }
    
    @Override
    public AppListOutput info(Short type) {
        AppEntity typeEntity = service.getOne(new QueryWrapper<AppEntity>().eq("type", type));
        AppListOutput output = modelUtil.mapToMap(typeEntity, AppListOutput.class);
        output.setEnable(appCinemaMapService.getEnabledStatusForAppIds(output.getId()));
        return output;
    }
    
    private void validateId(Long id) {
        if (service.isEmpty(id)) {
            throw new BadRequestException(
                ErrorCode.RECORD_NOT_EXIST,
                EscapeUtil.errorMessage("id", ErrorCode.RECORD_NOT_EXIST.getReasonPhrase())
            );
        }
    }
}
